<style>
    .layui-form-item .layui-inline {
        margin-top: 10px;
    }
</style>
<div class="layui-fluid" id="Ship-create">
    <div class="layui-card">
        <div class="layui-form" lay-filter="LAY-list-form">
            <div id="view"></div>
        </div>
    </div>
</div>
<script id="page1" type="text/html">
    <input type="hidden" name="id" value="{{layui.router().search.id||''}}">
    <div class="layui-card-header">发运计划资料</div>
    <div class="layui-card-body">
        <div class="layui-form-item">
            {{# if(layui.router().search.id>0){ }}
            <div class="layui-inline">
                <label class="layui-form-label">发运单号</label>
                <div class="layui-input-inline">
                    <span class="layui-input layui-input-none">{{d.plan.code||''}}</span>
                </div>
            </div>
            {{# } }}
            <div class="layui-inline">
                <label class="layui-form-label">*发货公司</label>
                <div class="layui-input-inline layui-jy-width200">
                    <input type="hidden" value="10002" name="company_id_out" class="layui-input ">
                    <span class="layui-input layui-input-none">{{d.info.company[10002]}}</span>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">*发货仓库</label>
                <div class="layui-input-inline">
                    <input type="hidden" value="30001" name="warehouse_id_out" class="layui-input ">
                    <span class="layui-input layui-input-none">{{d.info.warehouse[30001]||''}}</span>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">*收货仓库</label>
                <div class="layui-input-inline">
                    {{# if(layui.router().search.id>0&&layui.router().search.type!=2){ }}
                    <span class="layui-input layui-input-none">{{d.plan.warehouse_str_rec||''}}</span>
                    {{# }else{ }}
                    <select lay-filter="warehouse_id_rec" name="warehouse_id_rec" lay-verify="required" lay-search>
                        <option value="">请选择</option>
                        {{# for(var i in d.info.countryWarehouse){ if(i==d.plan.warehouse_id_rec){ var
                        selected='selected';}else{ var selected=''; } }}
                        <option value="{{i}}" {{selected}}>{{d.info.countryWarehouse[i]}}</option>
                        {{# } }}
                    </select>
                    {{# } }}
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">*收货国家</label>
                <div class="layui-input-inline">
                    <input id="country_id_rec" lay-verify="required" name="country_id_rec"
                           value="{{d.plan.country_str_rec||''}}"
                           type="hidden">
                    <span id="country_str_rec"
                          class="layui-input layui-input-none">{{d.plan.country_str_rec||''}}</span>
                </div>
            </div>


            <div class="layui-inline">
                <label class="layui-form-label layui-label-jy">*收货贸易公司</label>
                <div class="layui-input-inline">
                    <input id="trading_company" name="trading_company" lay-verify="required" value="{{d.plan.trading_company||''}}" type="hidden">
                    <span id="trading_str_company"
                          class="layui-input layui-input-none layui-jy-width200">{{d.plan.trading_str_company||''}}</span>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label layui-label-jy">*收货零售公司</label>
                <div class="layui-input-inline">
                    <input id="retail_company" name="retail_company" lay-verify="required" value="{{d.plan.retail_company||''}}" type="hidden">
                    <span id="retail_str_company" class="layui-input layui-input-none layui-jy-width200">{{d.plan.retail_str_company||''}}</span>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label  layui-label-jy">*最早发运时间</label>
                <div class="layui-input-inline">
                    {{# if(layui.router().search.id>0&&layui.router().search.type!=2){ }}
                    <span class="layui-input layui-input-none">{{d.plan.ship_time_early||''}}</span>
                    {{# }else{ }}
                    <input type="text" name="ship_time_early" class="layui-input" id="fy1Time" placeholder="yyyy-MM-dd"
                           lay-verify="required">
                    {{# } }}
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label layui-label-jy">*最晚发运时间</label>
                <div class="layui-input-inline">
                    {{# if(layui.router().search.id>0&&layui.router().search.type!=2){ }}
                    <span class="layui-input layui-input-none">{{d.plan.ship_time_late||''}}</span>
                    {{# }else{ }}
                    <input type="text" name="ship_time_late" class="layui-input " id="fy2Time" placeholder="yyyy-MM-dd"
                           lay-verify="required">
                    {{# } }}
                </div>
            </div>
            {{# if(layui.router().search.type>0){}}
            <div class="layui-inline">
                <label class="layui-form-label">海外公司</label>
                <div class="layui-input-inline">
                    <span class="layui-input layui-input-none">{{d.plan.company_str_overseas||''}}</span>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">创建人</label>
                <div class="layui-input-inline">
                    <span class="layui-input layui-input-none">{{d.plan.user||''}}</span>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">创建时间</label>
                <div class="layui-input-inline">
                    <span class="layui-input layui-input-none">{{d.plan.ctime||''}}</span>
                </div>
            </div>
            {{# } }}
        </div>
    </div>

    <div class="layui-card-header">商品信息</div>
    <div class="layui-card-body">
        <div class="layui-tab">
            <ul class="layui-tab-title">
                <li class="layui-this">明细信息</li>
                <li>头程信息</li>
            </ul>
            <div class="layui-tab-content">
                <div class="tab1 layui-tab-item layui-show">
                    <div class="layui-item">
                        {{# if(!layui.router().search.id) { }}
                        <button class="uploadPage layui-btn">导入</button>
                        <button class="add layui-btn">新增</button>
                        {{#} }}
                        <button class="export1 layui-btn">导出</button>
                        {{# if(layui.router().search.type==2) { }}
                        <button class="uploadPage2 layui-btn">导入标记</button>
                        {{#} }}
                    </div>
                    <table id="LAY-list" lay-filter="LAY-list"></table>
                </div>
                <div class="tab2 layui-tab-item">
                    <table id="LAY-list2" lay-filter="LAY-list2"></table>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-card-body layui-jy-center">
        <a lay-href="Ship/index" class="layui-btn">返回</a>
        {{# if(layui.router().search.type==2||!layui.router().search.id) { }}
        <input type="button" lay-submit lay-filter="LAY-submit-1" value="保存" class="layui-btn LAY-submit1">
        {{#} }}
    </div>

</script>
<!-- 行内工具 -->
<script type="text/html" id="LAY-list-toolbar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="del" href="javascript:;">删除</a>
</script>
<script>
    layui.use(['admin', 'form', 'toolJ', 'laytpl', 'laydate', 'upload', 'table', 'element'], function () {
        var $ = layui.$
            , form = layui.form
            , laytpl = layui.laytpl
            , setter = layui.setter
            , laydate = layui.laydate
            , table = layui.table
            , toolJ = layui.toolJ;
        var id = layui.router().search.id;
        var type = layui.router().search.type;
        var element = layui.element;
        //新增
        $('#Ship-create').off('click.add').on('click.add', '.add', function () {
            table.cache["LAY-list"].unshift({
                "shop_id": 0,
                "shop_str": '',
                "sku": "",
                "sku_name": "",
                "sku_enname": "",
                "ean": "",
                "demand_quantity": 0,
                "real_quantity": 0,
                "unit_volume": 0,
                "total_volume": 0,
                "unit_price": 0
            });
            tableView(table.cache["LAY-list"]);
        })
        //监听上传按钮
        $('#Ship-create').off('click.uploadPage').on('click.uploadPage', '.uploadPage', function () {
            if (typeof layui.table.cache['LAY-list'] != 'undefined' && table.cache['LAY-list'].length > 0) {
                layer.confirm('已存在数据,重新导入会将之前导入的清空是否确定!', function () {
                    upload();
                });
            } else {
                upload();
            }
        })
        //标记上传 '/index/Ship/upload', '/attachment/importcvs/shipdetail.csv',
        $('#Ship-create').off('click.uploadPage2').on('click.uploadPage2', '.uploadPage2', function () {
            if (typeof layui.table.cache['LAY-list'] != 'undefined' && table.cache['LAY-list'].length > 0) {
            } else {
                layer.alert('不存在明细!')
                return;
            }
            layer.open({
                title: '上传',
                type: 1,
                skin: 'layui-layer-rim', //加上边框
                area: ['420px', '240px'], //宽高
                content: '<div style="width: 280px; margin: 0 auto; margin-top: 64px;">' +
                    '<button type="button" style="margin-right: 20px" class="layui-btn" id="layUploadBtn"><i class="layui-icon"></i>上传文件</button>' +
                    '<a href="/attachment/importcvs/shipsign.csv" class="layui-btn layui-btn-primary"><i class="layui-icon"></i>下载模板</a>' +
                    '</div>'
            });
            //上传文件 指定允许上传的文件类型
            layui.upload.render({
                elem: '#layUploadBtn'
                , data: {"list": JSON.stringify(table.cache['LAY-list'])}
                , url: '/index/Ship/uploadSign'
                , accept: 'file' //普通文件
                , exts: 'csv' //只允许上传csv文件
                , done: function (res) {
                    layer.closeAll();
                    if (res.code == 1) {
                        if (res.msg) {
                            layer.msg(res.msg);
                        }
                        tableView2(res.data);
                    } else {
                        layer.alert(res.msg);
                    }
                }
                , before: function () {
                    layer.alert('执行中,请勿做其他操作!');
                    layer.load(1, {
                        shade: [0.5, '#fff']
                    });
                }
                , error: function () {
                    layer.closeAll();
                    layer.alert('失败,请稍后再试!');
                }
            });
        })
        //导出
        $("body").off('click.export1').on('click.export1', '.export1', function () {
            $(".layui-inline[lay-event='LAYTABLE_EXPORT']").click();
            $(".tab1 li[data-type='csv']").click();
        })

        function tableView(data) {
            var url = '';
            var jdata = '';
            if (data.length > 0) {
                jdata = data;
            } else {
                url = 'index/Ship/detail';
            }
            table.render({
                elem: '#LAY-list'
                , url: url
                , data: jdata
                , toolbar: true
                , defaultToolbar: ['exports', 'filter', 'print']
                , cellMinWidth: 80
                , cols: [[
                    {field: 'shop_str', title: '店铺', edit: 'text'}
                    , {field: 'sku', title: 'sku', edit: 'text'}
                    , {field: 'sku_name', title: '采购名称'}
                    , {field: 'sku_enname', title: '英文名称'}
                    , {field: 'ean', title: 'EAN码'}
                    , {field: 'demand_quantity', title: '理论需求量', edit: 'text'}
                    , {field: 'real_quantity', title: '实际计划发货量', edit: 'text'}
                    , {field: 'unit_volume', title: '单位体积', edit: 'text'}
                    , {field: 'total_volume', title: '总体积'}
                    , {field: 'unit_price', title: '单价'}
                    , {title: '操作', width: 70, align: 'center', fixed: 'right', toolbar: '#LAY-list-toolbar'}
                ]]
                , page: false
                , limit: 100000
                ,text:{none: '暂无相关数据!' }
            });
        }

        //详情
        function tableView2(data) {
            table.render({
                elem: '#LAY-list'
                , data: data
                , toolbar: true
                , defaultToolbar: ['exports', 'filter', 'print']
                , cellMinWidth: 80
                , cols: [[
                    {field: 'shop_str', title: '店铺'}
                    , {field: 'sku', title: 'sku'}
                    , {field: 'sku_name', title: '采购名称'}
                    , {field: 'sku_enname', title: '英文名称'}
                    , {field: 'ean', title: 'EAN码'}
                    , {field: 'ybr_str_status', title: '预报结果'}
                    , {field: 'demand_quantity', title: '理论需求量', edit: 'text'}
                    , {field: 'real_quantity', title: '实际计划发货量', edit: 'text'}
                    , {field: 'unit_volume', title: '单位体积', edit: 'text'}
                    , {field: 'total_volume', title: '总体积'}
                    , {field: 'unit_price', title: '单价'}
                    , {field: 'yb_str_status', title: '预报状态'}
                    , {field: 'yb_opinion', title: '预报意见'}
                    , {field: 'bh_str_status', title: '仓库状态'}
                    , {field: 'delivery_quantity', title: '出库数量'}
                ]]
                , page: false
                , limit: 100000
                ,text:{none: '暂无相关数据!' }
            });
        }

        function upload() {
            //第一个链接为上传api 第二个链接是模板下载链接 第三个是成功回调
            toolJ.upload('/index/Ship/upload', '/attachment/importcvs/shipdetail.csv', function (res) {
                if (res.code == 1) {
                    tableView(res.data);
                }
            });
        }

        function viewHtml(data) {
            var getTpl = page1.innerHTML
                , view = $('#view');
            laytpl(getTpl).render(data, function (html) {
                view.html(html);
            });
            laydate.render({
                elem: '#fy1Time'
                , value: data.plan.ship_time_early ? data.plan.ship_time_early : ''
            });
            laydate.render({
                elem: '#fy2Time'
                , value: data.plan.ship_time_late ? data.plan.ship_time_late : ''
            });
            if (data.type == 1) {
                tableView2(data.detail);
            } else {
                tableView(data.detail);
            }
            table.render({
                elem: '#LAY-list2'
                , url: '/index/Ship/logistics?code=' + data.plan.code
                , cellMinWidth: 80
                , cols: [[
                    {field: 'local_order_no', title: '物流内单号'}
                    , {field: 'box_number', title: '箱唛号'}
                    , {field: 'booking_space_date', title: '订舱日期'}
                    , {field: 'Shipment_date', title: '仓库出货日期'}
                    , {field: 'receiving_goods_date', title: '货代收货日期'}
                    , {field: 'out_customs_clearance_date', title: '出口清关日期'}
                    , {field: 'reality_departure_date', title: '实际离港日期'}
                    , {field: 'reality_arrival_date', title: '实际抵港日期'}
                    , {field: 'in_customs_clearance_date', title: '进口清关日期'}
                    , {field: 'reality_send_date', title: '实际派送日期'}
                    , {field: 'goods_online_date', title: '货物上架日期'}
                    , {field: 'quantity', title: '签收数量'}
                ]]
                , page: false
                , limit: 100000
                ,text:{none: '暂无相关数据!' }
            });


            table.render(null, 'LAY-list');
            table.render(null, 'LAY-list2');
            form.render(null, 'LAY-list-form');

            form.on('select(warehouse_id_rec)', function (d) {
                //选仓库自动带出国家
                if (d.value) {
                    $('#country_id_rec').val(data.info.warehouseCountry[d.value]);
                    $('#country_str_rec').text(data.info.warehouseCountry[d.value]);
                    //自动带出贸易公司和零售公司
                    toolJ.ajax({"url":"/index/Ship/getCompanyType?name="+data.info.warehouseCountry[d.value]},function (companyData) {
                        if(!companyData.data.ls){
                            toolJ.error('收货国家对应的零售公司不存在,请到基础设置添加!');
                        }
                        if(!companyData.data.my){
                            toolJ.error('收货国家对应的贸易公司不存在,请到基础设置添加!');
                        }
                        $("#trading_company").val(companyData.data.my.id);
                        $("#trading_str_company").text(companyData.data.my.company_name);
                        $("#retail_company").val(companyData.data.ls.id);
                        $("#retail_str_company").text(companyData.data.ls.company_name);
                    });
                } else {
                    $('#country_id_rec').val('');
                    $('#country_str_rec').text('');
                }
            });

            //监听提交
            form.on('submit(LAY-submit-1)', function (data) {
                if (typeof table.cache['LAY-list'] != 'undefined' && table.cache['LAY-list'].length > 0) {
                    data.field.list = JSON.stringify(table.cache['LAY-list']);
                    toolJ.ajax({"data": data.field});
                } else {
                    toolJ.error('不存在明细!');
                }
            })
            //监听行内操作
            table.on('tool(LAY-list)', function (obj) {
                switch (obj.event) {
                    case 'del':
                        layer.confirm('确定删除这条数据吗？', function (index) {
                            obj.del();
                            layer.close(index);
                        });
                        break;
                }
            });

        }

        var info = {};
        info.shop = layui.data(setter.tableName).shop;
        info.warehouse = layui.data(setter.tableName).warehouse;
        info.company = layui.data(setter.tableName).company;
        info.warehouseCountry = layui.data(setter.tableName).warehouseCountry;
        if (id) {
            toolJ.ajax({"data": {"id": id}, "type": "get"},
                function (data) {
                    info.myCompany = data.data.myCompany;
                    info.lsCompany = data.data.lsCompany;
                    info.countryWarehouse = data.data.countryWarehouse;
                    viewHtml({"info": info, "plan": data.data.plan, "type": 1, "detail": data.data.detail});
                }
            );
        } else {
            toolJ.ajax({"data": {}, "type": "get"},
                function (data) {
                    info.myCompany = data.data.myCompany;
                    info.lsCompany = data.data.lsCompany;
                    info.countryWarehouse = data.data.countryWarehouse;
                    viewHtml({"info": info, "plan": {}, "detail": {"code": 1, "data": null}, "type": 0});
                }
            );
        }
        table.on('edit(LAY-list)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            //编辑sku更新 更新sku相关字段
            if (obj.field == 'sku') {
                obj.data.sku = obj.value.toUpperCase();
                $.ajax({
                    type: 'post',
                    url: '/index/common/getSku',
                    dataType: 'json',
                    data: {"sku": obj.data.sku},
                    success: function (data) {
                        obj.update(
                            {"sku_name": "", "sku_enname": "", "unit_price": 0, "ean": ""}
                        );
                        if (data.code == 1) {
                            obj.data.sku_name = data.data.cnname;
                            obj.data.sku_enname = data.data.enname;
                            obj.data.unit_price = data.data.weighting_price;
                            obj.data.ean = data.data.ean;
                            obj.update(
                                obj.data
                            );
                        }
                    }
                })
            } else if (obj.field == 'shop_str') {
                //更改店铺
                var ok = 0;
                obj.update(
                    {"shop_id": 0}
                );
                for (var i  in info.shop) {
                    if (obj.value == info.shop[i]) {
                        obj.data.shop_id = i;
                        obj.update(
                            obj.data
                        );
                        ok = 1;
                    }
                }
                if (ok != 1) {
                    layer.alert('输入错误,店铺:' + obj.value + ' 不存在!');
                }
            } else {
                //重算体积
                obj.data.total_volume = obj.data.unit_volume * obj.data.real_quantity;
                obj.update(
                    obj.data
                );
            }
        });

    })
</script>